package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/*
*菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;


    //新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功!");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(name != null,Dish::getName,name);
        //添加排序条件
        lqw.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,lqw);

        //分析:上述查询的分页对象中,LIst<Dish> 数据中,每一个Dish对象,没有分页名称
        //创建新的分页对象
        Page<DishDto> dtoPage = new Page<>();
        //进行对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");//records属性,分页查询的集合数据,数据是需要处理的 因此我们不拷贝
        //获取基本分页查询的集合数据
        List<Dish> records = pageInfo.getRecords();
        ArrayList<DishDto> dtoList = new ArrayList<>();
        //遍历菜品集合
        records.forEach(dish -> {
            //将Dish拷贝到DishDto
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(dish,dto);

            //查询每个菜品所属分类名称
            Category category=categoryService.getById(dish.getCategoryId());
            dto.setCategoryName(category.getName());

            //放入集合中
            dtoList.add(dto);

        });

        //将dtolist集合,添加到dtoPage分页对象中
        dtoPage.setRecords(dtoList);

        //返回分页对象数据
        return R.success(dtoPage);
    }

    //根据id查询
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    //修改数据
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        return R.success("修改成功!");
    }

    //显示菜品
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

    //启售&禁售
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("status:{}",status);
        log.info("ids:{}",ids);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids != null,Dish::getId,ids);
        //根据数据进行批量查询
        List<Dish> list = dishService.list(lqw);

        for (Dish dish : list) {
            if(dish != null){
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }

        return R.success("售卖状态修改成功!");

    }

    //批量删除或者单个删除
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        //根据菜品id 在stemeal_dish表中查出哪些套餐包含该菜品
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.in(SetmealDish::getDishId,ids);
        List<SetmealDish> list = setmealDishService.list(lqw);
        //如果菜品没有关联套餐 就可以删除
        if(list.size() == 0){
            //deleteByIds中有菜品起售状态无法删除的操作
            dishService.deleteByIds(ids);
            LambdaQueryWrapper<DishFlavor> lam =new LambdaQueryWrapper<>();
            lam.in(DishFlavor::getDishId,ids);
            dishFlavorService.remove(lam);
            return R.success("菜品删除成功");
    }
        //如果菜品有关联套餐，并且该套餐正在售卖，那么不能删除
        //得到与删除菜品关联的套餐id
        ArrayList<Long> setmealList = new ArrayList<>();
        for(SetmealDish setmealDish:list){
            Long setmealId = setmealDish.getSetmealId();
            setmealList.add(setmealId);
        }
        //查询出与删除菜品相关联的套餐
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId,setmealList);
        List<Setmeal> setmealList1 = setmealService.list(lambdaQueryWrapper);

        //对拿到的所有套餐进行遍历 然后拿到套餐的售卖状态,如果有套餐正在售卖 那么删除失败
        for (Setmeal setmeal : setmealList1) {
            Integer status = setmeal.getStatus();
            if(status == 1){
                return R.error("删除的菜品中关联在售套餐,删除失败!");
            }
        }
        //要删除的菜品关联的套餐没有在售，可以删除
        //这下面的代码并不一定会执行,因为如果前面的for循环中出现status == 1,那么下面的代码就不会再执行
        dishService.deleteByIds(ids);
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(queryWrapper);

        return R.success("菜品删除成功!");
    }
}
